package com.muapet.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

public class MyFileUpload {
	private static final DateFormat dfyMd = new SimpleDateFormat("yyyyMMdd");
	private static final DateFormat dfHms = new SimpleDateFormat("HHmmss");
	public String writeImg(MultipartFile image,String basePath) {

		if (image.getSize() <= 0) {
			return "";
		}

		String savePath = basePath;//绝对路径

		String saveUrl = basePath;//数据库记录字段

		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}

		//按日期分文件夹
		String ymd = dfyMd.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		String hms = dfHms.format(new Date());
		String fileName = image.getOriginalFilename();
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toLowerCase();
		String newFileName = hms + "_" + new Random().nextInt(1000) + "."
				+ fileExt;

		FileOutputStream fos = null;
		InputStream is = null;
		try {
			is = image.getInputStream();
			fos = new FileOutputStream(savePath + newFileName);
			byte[] b = new byte[1024];
			int count = 0;
			while ((count = is.read(b)) > 0) {
				fos.write(b, 0, count);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return saveUrl + newFileName;
	}
}
